package Retail;

import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RetailProductInsert extends HttpServlet {
 @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException {
	// TODO Auto-generated method stub
	doProcess(req, resp);
}
 
 @Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProcess(req, resp);
	}
 
 protected void doProcess(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
	 
	   
		String tProductID= req.getParameter("ProductID");
		System.out.print(tProductID);
		if (tProductID !=null){
		String tProductDesc = req.getParameter("ProductDesc");
		BigDecimal tProductPrice= new BigDecimal(req.getParameter("ProductPrice"));
		BigDecimal tProductCost= new BigDecimal(req.getParameter("ProductCost"));
		BigDecimal tProductQuantity= new BigDecimal(req.getParameter("ProductQuantity"));
		int tProductVaildDate= Integer.parseInt(req.getParameter("ProductVaildDate"));
		String d = req.getParameter("ProductEntryDate");
		System.out.print(d);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date tProductEntryDate = null;
		try {
			tProductEntryDate = sdf.parse(d.toString());
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} 
		
		
		try {
			Class.forName("org.h2.Driver");
			Connection con = DriverManager.getConnection("jdbc:h2:~/retail",
					"sa", "");
			PreparedStatement ps = con.prepareStatement("Insert into PRODUCT values(?,?,?,?,?,?,?)");
			ps.setString(1, tProductID);
			ps.setString(2, tProductDesc);
			ps.setBigDecimal(3, tProductPrice);
			ps.setBigDecimal(4, tProductCost);
			ps.setBigDecimal(5, tProductQuantity);
			ps.setInt(6, tProductVaildDate);
			ps.setDate(7, new java.sql.Date(tProductEntryDate.getTime()));
			
			
			 ps.executeUpdate();
			
			ps.close();
			con.close();
			resp.sendRedirect("Product/ProductMain.jsp");	
		
	}catch (ClassNotFoundException e) {
		resp.sendRedirect("Product/ProductNotFound.jsp");
	} catch (SQLException e) {
		resp.sendRedirect("Product/ProductNotFound.jsp");
	}
		}
		else{
		req.getRequestDispatcher("Product/ProductInsert.jsp").forward(req, resp);	
		}
 }
 
}
